import React, { useState, useEffect } from 'react';
import './DataO.scss'
import { NavLink, useNavigate } from 'react-router-dom';
import { Input, Button, Table, Radio, Switch, message, Modal } from 'antd'
import { ExclamationCircleFilled } from '@ant-design/icons'
import ExportJsonExcel from "js-export-excel"
import { getOrglist, deleteOrg, patchOrg, updateOrgState, searchOrg } from '../../../../api/Datas'
interface Props {

}

const { Search } = Input;
const { confirm } = Modal;
function DataOrganization(props: Props) {
    const [selectionType, setSelectionType] = useState<'checkbox' | 'radio'>('checkbox');
    var [truelist, setTruelist] = useState([])
    var [list, setList] = useState([])
    var [key, setKey] = useState('')
    var navigate = useNavigate()
    var [loading, setLoading] = useState(false)
    var [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 100 })
    const [messageApi, contextHolder] = message.useMessage()
    // 挂载阶段
    useEffect(() => {
        getList()
        setPagination({
            ...pagination, total: list.length
        })
    }, [])
    // 获取机构列表
    var getList = async () => {
        var res = await getOrglist()
        console.log(res)
        if (res.data.code == 200) {
            console.log(res.data)
            setList(res.data.data)
            setLoading(false)
        }

    }
    // 点击搜索的时候
    const onSearch = async (value: string) => {
        var res = await searchOrg({ mechanismName: value })
        setList(res.data.data)
        if (value !== '' && res.data.data.length) {
            message.success({ content: '查询成功' })
        } else if (value !== '' && !res.data.data.length) {
            message.warning({ content: '暂时没有此条数据' })
        }
    }
    // 多选
    const rowSelection = {
        onChange: (selectedRowKeys: any, selectedRows: any) => {
            console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
            setTruelist(selectedRowKeys)
        }
    }

    // 点击删除
    const showConfirm = (id: any) => {
        confirm({
            title: '删除确认',
            icon: <ExclamationCircleFilled />,
            content: '机构信息删除后无法恢复，确定删除吗？',
            okText: "确认",
            cancelText: "取消",
            onOk() {
                deleteOrg({ id }).then((res: any) => {
                    console.log(res)
                    if (res.data.code == 200) {
                        message.success({ content: '删除机构成功' })
                        getList()
                    }
                })
            },
            onCancel() {
                console.log('已取消');
            },
        });
    }
    // 改变状态
    const onChange = async (checked: any, id: any) => {
        var res = await updateOrgState({ id: id })
        console.log(res)
        if (checked) {
            message.success({ content: '已启用' })
        } else {
            message.success({ content: '已禁用' })
        }
    }
    // 表格
    const columns = [
        {
            title: '编号', //表格头的标题
            dataIndex: 'mechanismId', //数据索引，决定通过哪个属性名（字段名）获取数据
            key: 'mechanismId',
        },
        {
            title: '机构图片',
            dataIndex: 'mechanismPicture',
            key: 'mechanismPicture',
            render: (_: any, record: any) => {
                return (
                    <img src={record.mechanismPicture} alt={record.img} />
                )
            }
        },
        {
            title: '机构名称',
            dataIndex: 'mechanismName',
            key: 'mechanismName',
        },
        {
            title: '负责人姓名',
            dataIndex: 'mechanismChargename',
            key: 'mechanismChargename',
        },
        {
            title: '电话',
            dataIndex: 'mechanismTelephone',
            key: 'mechanismTelephone',
        },
        {
            title: '机构地址',
            dataIndex: 'mechanismAddress',
            key: 'mechanismAddress',
        },
        {
            title: '状态',
            dataIndex: 'mechanismState',
            key: 'mechanismState',
            render: (_: any, record: any) => {
                return (
                    <Switch checkedChildren="启用" unCheckedChildren="禁用" defaultChecked={record.mechanismState} onChange={(checked, id) => { onChange(checked, record.mechanismId) }} />
                )
            }
        },
        {
            title: '操作',
            dataIndex: 'handle',
            key: 'handle',
            render: (_: any, record: any) => { //动态渲染当前列的数据，和dataIndex有冲突
                return (
                    <>
                        <NavLink className='pen' to='/index/datas-organization-handleorg' state={record}>编辑</NavLink>
                        <a className='delete' onClick={(id) => { showConfirm(record.mechanismId) }}>删除</a>
                    </>
                )
            }
        },
    ]
    // 点击新增
    const addOrg = () => {
        navigate('/index/datas-organization-addorg')
    }
    // 分页发生改变后执行
    const handleChange = (pagi: any) => {
        setPagination(pagi) //更新页码
        setLoading(true)
        // 请求新的页码对应的数据
        getOrglist().then(res => {
            if (res.status == 200) {
                setLoading(false)
                setPagination({
                    ...pagi, total: res.data.length
                })

            }
        })
    }
    let excel = () => {//导出Excel表
        let sheetFilter = ["mechanismId", "mechanismPicture", 'mechanismName', 'mechanismChargename', 'mechanismTelephone', "mechanismAddress", "mechanismState"]//需要导出的属性，一般列表数据的属性
        let option = { fileName: "", datas: [{}] };
        option.fileName = "待处理服务列表";
        option.datas = [
            {
                sheetData: list,//需要导出的数据
                sheetName: "待处理服务列表",
                sheetFilter: sheetFilter,
                sheetHeader: ["编号", "机构图片", "机构名称", "负责人姓名", "电话", "机构地址", "状态"],//每一列的列头
                columnWidth: [20, 20, 20, 20],//每一列的宽
            }
        ]
        let toExcel = new ExportJsonExcel(option);
        toExcel.saveExcel();
    }
    return (
        <div className='data-organization'>
            <div className="title">
                <div className='leftborder'></div>
                <h3>机构管理</h3>
            </div>
            <div className="inputbox">
                <Search placeholder="请输入机构名称关键字" allowClear onSearch={onSearch} style={{ width: 300 }} />
                <div className="btnbox">
                    <Button type="primary" onClick={addOrg}>新增机构</Button>
                    <Button onClick={excel}>导出</Button>
                </div>
            </div>
            <Radio.Group
                onChange={({ target: { value } }) => {
                    setSelectionType(value);
                }}
                value={selectionType}
            >
            </Radio.Group>
            {/* <Table columns={columns} dataSource={list} pagination={pagination} onChange={(pagi)=>{handleChange(pagi)}} loading={loading}/> */}
            <Table
                rowSelection={{
                    type: selectionType,
                    ...rowSelection,
                }}
                pagination={pagination}
                onChange={(pagi) => { handleChange(pagi) }}
                loading={loading}
                dataSource={list}
                columns={columns} />
        </div>
    );
}

export default DataOrganization;